/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var follow_offset = 0;
var request_offset = 0;
var followed_offset = 0;
var limit = 10;
var userId = '';

var FOLLOW_LIST = 0;
var REQUEST_LIST = 1;
var FOLLOWED_LIST = 2;

/**
 * After Login.
 */
function afterLogin() {
	loadProfile();
	initialize();
}

/**
 * Load Profile facebook.
 */
function loadProfile() {
	// load user account from cookie
	var useraccount = $.cookie('useraccount');
	if (useraccount != '' && useraccount != null) {
		$.ajax({
			url : "/search?action=initMap&userId=" + useraccount,
			type : 'GET',
			data : '',
			success : function(resp) {
				if (resp != null) {
					// getting the data from the response object
					var data = resp.data;
					// initialize map
					if (data.length > 0) {
						PhonemapUtil.setProfile(data[0]);
					}
				}
			},
			error : function(resp) {
				alert('Cannot get data! Please check again');
			}
		});
	} else {// not login
		// Go to index page
		document.location.href = '/login.html';
	}
}

/**
 * lookup Follow.
 */
function lookupFollow(followId) {
	//var userId = $.cookie('useraccount');
	$.ajax({
		url : "/follow?action=isExist&userId=" + userId + "&followId="
				+ followId,
		type : 'GET',
		data : '',
		success : function(resp) {
			if (resp != '' && resp != null) {
				var data = resp.data;
				if (data.length > 0) {
					var follow = data[0];
					if (follow.status == PhonemapConstant.NULL) {
						$("#F" + followId).text("Request");
						$("#F" + followId).attr('data-status', '-1');
					} else if (follow.status == PhonemapConstant.REQUESTING){
						$("#F" + followId).text("Requesting");
						$("#F" + followId).attr('disabled', 'disabled');
						$("#F" + followId).attr('data-status', '0');
					} else if (follow.status == PhonemapConstant.CONFIRMED){
						$("#F" + followId).text("Unfollow");
						$("#F" + followId).attr('data-status', '1');
					} else {
						$("#F" + followId).text("Unfollow");
						$("#F" + followId).attr('data-status', '1');
					} 
				} else {
					$("#F" + followId).text("Request");
					$("#F" + followId).attr('data-status', '-1');
				}
			}
		},
		error : function(resp) {
			alert('Cannot update! Please check again');
		}

	});
}

/**
 * update Follow.
 * @param followId
 */
function updateFollow(followId) {
	var userId = $.cookie('useraccount');
	var checked; //= $("#" + followId).prop('checked');
	var status = $("#F" + followId).attr('data-status');
	if (status != 'undefined') {
		if (status == '1') {
			checked = 'false';
		} else if (status == '-1') {
			checked = 'true';
		}
	}
		
	var friendName = $("#nameF" + followId).text();
	$.ajax({
		url : "/follow?action=update&userId=" + userId + "&followId="
				+ followId + "&checked=" + checked + "&friendName="
				+ friendName,
		type : 'POST',
		data : '',
		dataType : "html",
		success : function(resp) {
//			if (resp != '') {
				if (status != 'undefined') {
					if (status == '-1') {
						$("#F" + followId).text("Requesting");
						$("#F" + followId).attr('data-status', '0');
					} else if (status == '1') {
						$("#F" + followId).text("Request");
						$("#F" + followId).attr('data-status', '-1');
					}
				}
//			}
		},
		error : function(resp) {
			alert('Cannot update! Please check again');
		}

	});
}

/**
 * confirm Follow.
 * @param followId
 */
function confirmFollow(followId) {
	var userId = $.cookie('useraccount');
	var checked; //= $("#" + followId).prop('checked');
	var status = $("#R" + followId).attr('data-status');
	if (status != 'undefined') {
		if (status == '0') {
			var friendName = $("#nameR" + followId).text();
			$.ajax({
				url : "/follow?action=confirm&userId=" + userId + "&followId="
						+ followId + "&checked=" + checked + "&friendName="
						+ friendName,
				type : 'POST',
				data : '',
				dataType : "html",
				success : function(resp) {
//					if (resp != '') {
						if (status != 'undefined') {
							if (status == '0') {
								$("#R" + followId).text("Unaccepted");
								$("#R" + followId).attr('data-status', '1');
							} 
						}
//					}
				},
				error : function(resp) {
					alert('Cannot update! Please check again');
				}

			});
		}
	}
		
	
};

/**
 * Gets LI Item
 * @param input
 * @param type
 * @returns {String}
 */
function getLIItem(id, name, type) {
	var liItem = "";
	liItem = liItem
			+ "<li class=\"item\"> <div > <a class=\"image lfloat\"> <img alt=\"\" src= ";
	liItem = liItem + "\"https://graph.facebook.com/" + id
			+ "/picture\"> </a> <div class= ";
	liItem = liItem
			+ "\"clearfix hidden\"> <div class=\"inline-block rfloat\"> <div class= ";
	liItem = liItem
			+ "\"inline-block middle\" style=\"height: 50px\"></div> <div class= ";
	liItem = liItem
			+ "\"inline-block middle\"> <div class=\"right\"> <div class=\"FollowButton\">";
	if (type == 0) {
		liItem = liItem +"<button "
		+ "type=\"button\" id=\"F"
		+ id
		+ "\" onclick=\"updateFollow('"
		+ id
		+ "')\"></button>";
	} else if (type == 1) {
		liItem = liItem +"<button "
		+ "type=\"button\" id=\"R"
		+ id
		+ "\" onclick=\"confirmFollow('"
		+ id
		+ "')\"></button>";
	} else if (type == 2) {
		liItem = liItem +"<button "
		+ "type=\"button\" id=\"FD"
		+ id
		+ "\" onclick=\"deleteFollow('"
		+ id
		+ "')\"></button>";
	}
	
	liItem = liItem + "</div> </div> </div> </div> <div class=\"blockContent\"> <div ";
	liItem = liItem
			+ "class=\"inline-block\"> <div class=\"inline-block middle\" style=\"height: 50px\"></div> ";
	if (type == 0) {
		liItem = liItem
		+ "<div class=\"inline-block middle\"> <div> <a href=\"#\" id=\"nameF"
		+ id + "\">" + name;
	} else if (type == 1) {
		liItem = liItem
		+ "<div class=\"inline-block middle\"> <div> <a href=\"#\" id=\"nameR"
		+ id + "\">" + name;
	} else if (type == 2) {
		liItem = liItem
		+ "<div class=\"inline-block middle\"> <div> <a href=\"#\" id=\"nameFD"
		+ id + "\">" + name;
	}
	
	liItem = liItem + "</a> </div> </div> </div> </div> </div> </div> </li> ";
	return liItem;
}

/**
 * load Results.
 */
function loadFriends() {
	//var result = "";

	FB.api('/me/friends?offset=' + follow_offset + '&limit=' + limit, function(
			response) {

		if (response.data != null) {
			var $followList = $("#followList");
			var friends = response.data;

			for (var int = 0; int < friends.length; int++) {
				var array_element = friends[int];
				// var item = '<li>'+index+'.'+array_element.name+'</li>'
				$followList.append(getLIItem(array_element.id, array_element.name, 0));
				lookupFollow(array_element.id);
			}
		}
	});
};

/**
 * Load requests.
 * @returns
 */
function loadRequests() {

	$.ajax({
		url : "/follow?action=getRequests&userId=" + userId +'&offset=' + request_offset,
		type : 'GET',
		data : '',
		success : function(resp) {
			if (resp != '' && resp != null) {
				var users = resp.data;
				if (users.length > 0) {
					var $requestList = $("#requestList");
					for (var i = 0, len = users.length; i < len; i++) {
						var user = users[i];
						$requestList.append(getLIItem(user.user_id, user.fullname, 1));
						$("#R" + user.user_id).attr('data-status', '0');
						$("#R" + user.user_id).text("Confirm");
					}
				}
			} else {
				request_offset = 0;
			}
		},
		error : function(resp) {
			alert('Cannot get data! Please check again');
		}

	});
}

/**
 * Load requests.
 * @returns
 */
function loadFollowed() {

	$.ajax({
		url : "/follow?action=getFollowedList&userId=" + userId +'&offset=' + followed_offset,
		type : 'GET',
		data : '',
		success : function(resp) {
			if (resp != '' && resp != null) {
				var users = resp.data;
				if (users.length > 0) {
					var $followedList = $("#followedList");
					for (var i = 0, len = users.length; i < len; i++) {
						var user = users[i];
						$followedList.append(getLIItem(user.user_id, user.fullname, 2));
						$("#FD" + user.user_id).attr('data-status', '0');
						$("#FD" + user.user_id).text("Remove");
					}
				}
			} else {
				request_offset = 0;
			}
		},
		error : function(resp) {
			alert('Cannot get data! Please check again');
		}

	});
}

function addLoadMore(type) {
	if (type == FOLLOW_LIST) {
		$("#followScroll").scroll(function() {
			var $this = $(this);
			var $followList = $("#followList");
			var scrollTop = $this.scrollTop();
			var height = $this.height();
			//var friendListHeight = $followList.height();
			if ($this.scrollTop() + $this.height() >= $followList.height()) {

				follow_offset += 10;
				loadFriends();
			}
		});
	} else if (type == REQUEST_LIST) {
		$("#requestScroll").scroll(function() {
			var $this = $(this);
			var $requestList = $("#requestList");
			var scrollTop = $this.scrollTop();
			var height = $this.height();
			//var friendListHeight = $followList.height();
			if ($this.scrollTop() + $this.height() >= $requestList.height()) {

				request_offset += 10;
				loadRequests();
			}
		});
	} else if (type == FOLLOWED_LIST) {
		$("#followedScroll").scroll(function() {
			var $this = $(this);
			var $followedList = $("#followedList");
			var scrollTop = $this.scrollTop();
			var height = $this.height();
			//var friendListHeight = $followList.height();
			if ($this.scrollTop() + $this.height() >= $followedList.height()) {

				followed_offset += 10;
				loadFollowed();
			}
		});
	}
}

/**
 * initialize
 */
function initialize() {
	
	userId = PhonemapUtil.getUserId();
	
	loadFriends();
	addLoadMore(FOLLOW_LIST);
	
	loadRequests();
	addLoadMore(REQUEST_LIST);
	
	loadFollowed();
	addLoadMore(FOLLOWED_LIST);
};

